{% load static %}
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>股票日历</title>
    <link rel="stylesheet" href="{% static '/css/jquery-ui.css' %}">
    <link href="{% static '/css/bootstrap.min.css' %}" rel="stylesheet" media="screen">
    <link href="{% static '/css/bootstrap-datetimepicker.min.css' %}" rel="stylesheet" media="screen">
    <script src="{% static '/js/jquery-1.12.4.js' %}"></script>
    <script src="{% static '/js/jquery-ui.js' %}"></script>
    <script type="text/javascript" src="{% static '/js/jquery-1.8.3.min.js' %}" charset="UTF-8"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap.min.js' %}"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap-datetimepicker.js' %}" charset="UTF-8"></script>
    <script type="text/javascript" src="{% static '/js/bootstrap-datetimepicker.zh-CN.js' %}" charset=
            "UTF-8"></script>
</head>
<body>
<div id="FP_chart" style="height: 88.5714%;width: 100.0%;">
    <canvas id="canvas_layer" width="30000" height="900" style="border: 1px solid #eeeeee;"></canvas>
    <div>
        <div id="indicator"
             style="position: absolute; z-index: 51; border-style: dashed; border-color: rgb(73, 73, 73);left : 10px; top: 20px; border-width: 0px 1px 0px 0px; height: 665px;"/>
    </div>
    <div>
        <div id="float_window"
             style="position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px; font-size: 12px; left: 60px; top: 30px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0); border: 1px solid rgb(0, 0, 0);">
		<canvas id="canv" width="300" height="200" style="border: 1px solid #eeeeee;"></canvas> 
		</div>
    </div>
	<div id= "tag_rela_codes_flow" style="position: absolute; z-index: 52; padding: 2px;height: 200px;width:500px;overflow:auto;background-color: rgba(255, 255, 255, 0.9);left: 360px; top: 30px;  border: 1px solid rgb(0, 0, 0);">
		<div class="container" style="width: 500px;">
		    <!--修改为输入股票时进行快速的推荐，-->
		    <!-- <input type="text" placeholder="股票代码或者名称" id="in_tag"> -->
		    <!-- <h2>标签历史涨停次数 : <b id="cur_count">1</b></h2> -->
		    <!-- <p>服务器时间: <b id="server_time">2019-01-01</b></p> -->
		    <table class="table table-hover text-left" id="tag_rela_codes_table" style="font-size: 7px;font-weight:bold;">
		        <thead>
		        <tr>
		            <th>列号</th>
		            <th>股票代码</th>
		            <th>股票名</th>
					<th>股票关联涨停</th>
		            <th>标签历史涨停</th>
		            <th>关联度</th>
		            <th>最近一次涨停时间</th>
		        </tr>
		        </thead>
		        <tbody>
		        </tbody>
		    </table>
		</div>
	</div>
	
</div>
<div class="container">
    <label class="labe_l">开始日期:</label>
    <div class="clearfix tex_t reset_text">
        <div class="input-append date fl" style="float:left" id="datetimeStart">
            <input type="text" class="">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <span class="to_link">至</span>
        <div class="input-append date fl" style="float:left" id="datetimeEnd">
            <input type="text" class="">
            <span class="add-on"><i class="icon-th"></i></span>
        </div>
        <input type="number" value="300" id="size">
        <input type="button" value="提交" id="submit_btn"/>
    </div>
</div>
<div class="container" style="top:300px;width: 1000px;">
    <!--修改为输入股票时进行快速的推荐，-->
    <h2>    <input type="text" placeholder="股票代码或者名称" id="in_tag"> 标签历史涨停次数 : <b id="cur_count">1</b></h2>
    <p>服务器时间: <b id="server_time">2019-01-01</b></p>
    <table class="table table-hover" style="width: 1000px;height: 100px; overflow: scroll;" id="tag_rela_codes_table__2">
        <thead>
        <tr>
            <th>序号</th>
            <th>股票代码</th>
            <th>股票名</th>
            <th>股票标签历史涨停次数</th>
            <th>关联度</th>
            <th>最近一次涨停时间</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div> 
</body>
<script>
    //日期插件初始化
    var nw = new Date();
    nw.setDate(nw.getDate() - 300)
    $('#datetimeStart').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        /*以星期一为一星期开始*/
        todayBtn: 1,
        autoclose: 1,
        minView: 2,
        initialDate: nw,
        /*精确到天*/
        pickerPosition: "bottom-left"
    }).on("changeDate", function (ev) { //值改变事件
        //选择的日期不能大于第二个日期控件的日期
        if (ev.date) {
            $("#datetimeEnd").datetimepicker('setStartDate', new Date(ev.date.valueOf()));
        } else {
            $("#datetimeEnd").datetimepicker('setStartDate', null);
        }
        console.log(($("#datetimeStart").datetimepicker().val()))
    });
    $('#datetimeEnd').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        weekStart: 1,
        /*以星期一为一星期开始*/
        todayBtn: 1,
        autoclose: 1,
        minView: 2,
        /*精确到天*/
        pickerPosition: "bottom-left"
    }).on("changeDate", function (ev) {
        //选择的日期不能小于第一个日期控件的日期
        if (ev.date) {
            $("#datetimeStart").datetimepicker('setEndDate', new Date(ev.date.valueOf()));
        } else {
            $("#datetimeStart").datetimepicker('setEndDate', new Date());
        }
    });
    //设置默认时间
    $("#datetimeEnd").datetimepicker('setStartDate', new Date());


</script>

</html>
<script>
	
	// 用于两个不同的canvas之间传递变量，从LChart传递到FloatChart
	cur_date_status = ''
	cur_tag_status = ''
	
    var LChart = function () {
        this.con = document.querySelector("canvas").getContext("2d");
        this.canW = this.con.canvas.width;
        this.canH = this.con.canvas.height;
        this.size = 10;
        this.space = 20;
        this.step = 30;
        this.x0 = this.space;
        this.dateheight = 100
        this.y0 = this.canH - this.space - this.dateheight;
        this.pointSize = 4;
        this.indicator = document.getElementById('indicator');
        this.tbodys = document.getElementById("tbodys")
        this.gaobiao_scale = 40;
        this.color_index = 0;
		this.float_window = document.getElementById('float_window');
	};
	
	
	var FloatChart = function () {
	    this.con = document.getElementById('canv').getContext('2d');
	    this.y0 = 20
		this.w = 10
	};
	FloatChart.prototype.drawFont = function (options, vertical) {
	    this.con.save();
	    this.con.fillStyle = options.color;
	    this.con.textAlign = options.textAlign || "center";
	    this.con.font = this.w * options.fontSizePercent + "px 宋体";
	    this.con.textBaseline = options.textBaseline || "bottom";
	    if (vertical) {
	        this.con.rotate(-45 * Math.PI / 180);
	    }
	    this.con.fillText(options.text, options.x, options.y);
	
	    this.con.restore();
	}
	float_chart_base_y = 0
	float_chart_shift_y = 0
	FloatChart.prototype.rectMatrix = function (data, index,cur_date, cur_tag) {
		if(cur_date == '' || cur_tag == ''){
			return;
		}
		// fixme 服务端获取对应的数据
		// var continue_stock_infos = NaN
		// continue_stock_infos = {"first_high_count":[{"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2","rela_ratio":"0.1"},
		//     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2","rela_ratio":"0.1"},
		//     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2","rela_ratio":"0.1"}], "second_high_count":[], "third_high_count":[], "forth_high_count":[],
	 //        "fifth_high_count":[{"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2","rela_ratio":"0.1"},
		//     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2","rela_ratio":"0.1"}]}
		// 需要进行遍历访问
		// for(var date_i in data){
		// 	if(data[date_i]['date'] == cur_date){
		// 		var tags_inces = data[date_i]['tags_inc']
		// 		for(var tag_inc_i in tags_inces){
		// 			if(tags_inces[tag_inc_i]['tag'] == cur_tag){
		// 				continue_stock_infos = tags_inces[tag_inc_i]['plate_info']
		// 				break;
		// 			}
		// 		}
		// 	}
		// }
		// 及时退出不画图
		try{
			continue_stock_infos = generate_continue_stock_infos_from_backend(cur_date, cur_tag)
			if(continue_stock_infos == NaN){
				return;
			}
			// 能够重新进行画的时候才进行清除
			fct.con.clearRect(0, 0, 30000, 30000)
			// "#ffcc00" , "#ff0000"
			var need_col_s = ["first_high_count", "second_high_count", "third_high_count", "forth_high_count",
			    "fifth_high_count"
			]
			var map_col_en_2_cn = {
			    "first_high_count": "一板",
			    "second_high_count": "二板",
			    "third_high_count": "三板",
			    "forth_high_count": "四板",
			    "fifth_high_count": "五板+"
			}
			var color = ""
			// 找出断层的位置
			// 找到 [1,3]中的第一个0
			var hasFault = false
			var idx = -1
			for (var nci in need_col_s) {
			    if (0 == nci) {
			        continue;
			    }
			    var nck = need_col_s[nci];
			    var ncv = continue_stock_infos[nck].length
			    if (0 == ncv) {
			        idx = nci
			        break;
			    }
			}
			if (idx != -1) {
			    // 向后进行遍历
			    for (var nci in need_col_s) {
			        if (nci <= idx) {
			            continue;
			        }
			        var ncv = need_col_s[nci]
			        if (continue_stock_infos[ncv].length > 0) {
			            hasFault = true
			            break;
			        }
			    }
			}
			if (hasFault) {
			    color = "#ff0000";
			} else {
			    color = "#ff9900";
			}
				
			this.con.fillStyle = color;
			var color_index = 0
			var lineH = 10;
			var base_y = this.y0; //柱形底部位置
			float_chart_base_y = base_y
			var shift_y = 30;
			float_chart_shift_y = shift_y
			var base_x = 60
			var val_shift = 3
			var x = 0;
			x += base_x;
			// width是需要出来的 height是固定的 base_x 固定 Y需要变化
			var y_idx = 0;
			
			var need_col_sr = ["first_high_count", "second_high_count", "third_high_count", "forth_high_count",
			    "fifth_high_count"
			].reverse()
			for (var nk in need_col_sr) {
			    var need_col = need_col_sr[nk]
			    var val = continue_stock_infos[need_col].length
			    var y = base_y + shift_y * y_idx
			    this.con.fillRect(base_x, y, val * val_shift, lineH); // startx starty width height
			    this.drawFont({
			        "text": map_col_en_2_cn[need_col],
			        "x": base_x - 40,
			        "y": y + lineH,
			        "fontSizePercent": 1.7,
			        "color": color
			    })
			    this.drawFont({
			        "text": val,
			        "x": base_x - 15,
			        "y": y + lineH,
			        "fontSizePercent": 1.7,
			        "color": color
			    })
			    this.con.fill();
			    this.con.restore();
			    y_idx++;
			}
			
		}catch(e){
			console.log(e)
		} 
	}
	FloatChart.prototype.monitorMouse = function(){
		// 对于连板的股票信息进行时间监听测试
		var little_themeor = document.getElementById("canv");
		little_themeor.addEventListener('mousemove', function (ev) {
		    ev = ev || window.event;
		    changeRelaCodes(ev.layerY);
		})
	}																					
	FloatChart.prototype.init = function(){
		// 对于连板的股票信息进行时间监听测试
		fct.monitorMouse()
	}	
    LChart.prototype.check_load_data = function () {
        lc.init();
        lc.monitorMouse();
    };

    LChart.prototype.transform_function_1 = function (data, object) {
        var transform = data * 10 + 100 - 2 * object.gaobiao_scale;
        return transform;
    }

    LChart.prototype.transform_function_2 = function (data) {
        var transform = data / 12;
        return transform;
    }

    LChart.prototype.transform_function_3 = function (data) {
        var transform = data / 2;
        return transform;
    }

    LChart.prototype.init = function () {
        // 计算范围
        this.con.clearRect(0, 0, 30000, 1000);
        x_date_length = 0
        for (var key in data) {
            var tags_len = data[key]['tags_inc'].length
            x_date_length += Math.max(tags_len, 1)
        }
        //this.huaGeZi();
        this.rectMatrix(data, this.gaobiao_scale);
        this.drawdate(data);
        this.drawline(0, 100, 100, 100, 'green')
    };
    LChart.prototype.huaGeZi = function () {
        var lineX = Math.floor(this.canH / this.size);
        for (var i = 1; i < lineX; i++) {
            this.con.beginPath();
            this.con.strokeStyle = "#eee";
            this.con.moveTo(0, i * this.size + 0.5);
            this.con.lineTo(this.canW, i * this.size + 0.5);
            this.con.stroke();
        }
        var lineY = Math.floor(this.canW / this.size);
        for (var j = 1; j < lineY; j++) {
            this.con.beginPath();
            this.con.strokeStyle = "#eee";
            this.con.moveTo(j * this.size + 0.5, 0);
            this.con.lineTo(j * this.size + 0.5, this.canH);
            this.con.stroke();
        }
    };

    LChart.prototype.drawline = function (startX, startY, endX, endY, color, line_width = 1) {
        this.con.beginPath();
        //X
        this.con.moveTo(startX, startY);
        this.con.lineTo(endX, endY);
        this.con.strokeStyle = color;
        this.con.lineWidth = line_width
        this.con.stroke();
    };

    LChart.prototype.zb = function () {
        this.con.beginPath();
        //X
        this.con.moveTo(this.x0, this.y0);
        this.con.lineTo(this.canW - this.space, this.y0);
        this.con.lineTo(this.canW - this.space - this.size, this.y0 + this.size / 2);
        this.con.lineTo(this.canW - this.space - this.size, this.y0 - this.size / 2);
        this.con.lineTo(this.canW - this.space, this.y0);
        this.con.fill();
        this.con.strokeStyle = "gray";
        this.con.stroke();
        //Y
        this.con.moveTo(this.x0, this.y0);
        this.con.lineTo(this.x0, this.space);
        this.con.lineTo(this.x0 + this.size / 2, this.space + this.size);
        this.con.lineTo(this.x0 - this.size / 2, this.space + this.size);
        this.con.lineTo(this.x0, this.space);
        this.con.fill();
        this.con.strokeStyle = "gray";
        this.con.stroke();
    };

    LChart.prototype.point = function (data, transform_function, color) {
        this.con.beginPath();
        var that = this;
        var prevX = 0;
        var prevY = 0;
        that.con.strokeStyle = color;
        for (var i = 0; i < data.length; i++) { //绘制柱形
            var canvasX = that.x0 + (i + 1) * this.step;
            var canvasY = that.y0 - transform_function(data[i], this) - 40;
            that.con.fillRect(canvasX - that.pointSize / 2, canvasY - that.pointSize / 2, that.pointSize, that.pointSize);
            if (i == 0) {
                that.con.moveTo(canvasX, canvasY);
            } else {
                that.con.moveTo(prevX, prevY);
                that.con.lineTo(canvasX, canvasY);
                that.con.stroke();
            }
            prevX = canvasX;
            prevY = canvasY;
        }
    };

    LChart.prototype.fillpoint = function (data, color, startX, startY, transform_function, reverse) {
        var that = this;
        var prevX = startX;
        var prevY = startY;
        that.con.beginPath();
        that.con.strokeStyle = color;
        that.con.fillStyle = color;
        var startx = 0;
        var starty = 0;
        for (var i = 0; i < data.length; i++) { //绘制柱形
            var canvasX = startX + (i + 1) * this.step;
            var offsetY = data[i];
            if (transform_function != null) {
                offsetY = transform_function(data[i]);
            }
            var canvasY = reverse ? startY - offsetY : startY + offsetY;
            if (i == 0) {
                startx = canvasX;
                starty = startY;
                that.con.moveTo(canvasX, canvasY);
            } else {
                that.con.lineTo(canvasX, canvasY);
            }
            prevX = canvasX;
            prevY = canvasY;
        }
        that.con.lineTo(prevX, startY);
        that.con.lineTo(startx, starty);
        //that.con.closePath();
        that.con.fill();
        this.con.restore();
    };


    LChart.prototype.drawRoundRect = function (x, y, width, height, radius, color) {
        this.con.fillStyle = color
        this.con.beginPath();
        this.con.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
        this.con.lineTo(width - radius + x, y);
        this.con.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
        this.con.lineTo(width + x, height + y - radius);
        this.con.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);
        this.con.lineTo(radius + x, height + y);
        this.con.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);
        this.con.closePath();
    }


    LChart.prototype.drawFont = function (options, vertical) {
        this.con.save();
        this.con.fillStyle = options.color;
        this.con.font = this.w * options.fontSizePercent + "px 宋体";
        this.con.textAlign = options.textAlign || "center";
        this.con.textBaseline = options.textBaseline || "bottom";
        if (vertical) {
            this.con.rotate(-45 * Math.PI / 180);
        }
        this.con.fillText(options.text, options.x, options.y);

        this.con.restore();
    }


    LChart.prototype.rectMatrix = function (data, amplify) {
        var hArrTop = 12; //直方图，柱形上方显示字体
        var pos = 100; //起始位置

        var lineWPercent = 0.25; //柱形宽度
        var rectRadiusPercent = 1 / 2; //柱形圆角大小


        color_index = 0
        var color_arr = ["DarkSeaGreen", "gray", "LightSteelBlue", "Sienna"]
        var strokeStyle = "gray"; //柱形颜色
        var topFontColor = "gray"; //柱形顶部文字颜色
        var topFontSizePercent = 1 / 25; //柱形顶部文字大小
        var isShadow = false;


        var lineW = 9; //柱形宽度
        var y = this.y0; //柱形底部位置

        if (isShadow) {
            this.con.save();
            this.con.shadowOffsetX = 5; //绘制阴影
            this.con.shadowOffsetY = 5;
            this.con.shadowBlur = 4;
            this.con.shadowColor = "rgba(0, 0, 0, 0.2)";
        }
        this.con.fillStyle = "rgba(0, 0, 0, 0.4)"; //填充柱形,颜色

        x_base = 1
        for (var dt in data) {
            var color = color_arr[color_index % color_arr.length]
            color_index++
            var pre_x_base = x_base
            // 没有数据的时候也需要绘制一个空格的地方
            if (data[dt]['tags_inc'].length == 0) {
                var x = this.x0 + this.step * (x_base)
                this.drawRoundRect(x - lineW / 2, this.y0 - 0 * amplify, lineW, 0 * amplify, lineW * rectRadiusPercent, color);
                this.con.fill();
                if (true) {
                    this.drawFont({
                        x: x,
                        y: y - 0 * amplify - 10,
                        text: '没有数据~~',
                        color: topFontColor,
                        fontSizePercent: topFontSizePercent
                    }, false);
                } //绘制文字
                x_base += 1
            } else {
                var tags_inc = data[dt]['tags_inc']
                for (var ti = 0; ti < tags_inc.length; ti++) {
                    one_tag_incr = tags_inc[ti]

                    var x = this.x0 + this.step * (x_base)
                    this.drawRoundRect(x - lineW / 2, this.y0 - calu_4_draw(one_tag_incr['incr'] * amplify), lineW, calu_4_draw(one_tag_incr['incr'] * amplify),
                        lineW *
                        rectRadiusPercent, color);
                    this.con.fill();
                    //画连线
                    if (true) {
                        this.drawFont({
                            x: x,
                            y: y - calu_4_draw(one_tag_incr['incr'] * amplify),
                            text: one_tag_incr['tag'],
                            color: topFontColor,
                            fontSizePercent: topFontSizePercent
                        }, false);
                    } //绘制文字
                    x_base += 1
                }
            }

            var start_x = this.x0 + this.step * (pre_x_base)
            var end_x = this.x0 + this.step * (x_base - 1)
            this.drawline(start_x, this.y0 - 5, end_x, this.y0 - 5, color, line_width = 10)
            this.drawline(start_x, this.y0 -calu_4_draw(8 * amplify) , this.x0 + this.step * (x_base), this.y0 -calu_4_draw(8 * amplify), 'black')
        }

        this.con.restore();
    }

    // func
    LChart.prototype.drawdate = function (data) {
        // 需要根据tag_inc.length*date.length 来算 最少要画一个
        var lineW = 9; //柱形宽度
        var y = this.y0; //柱形底部位置
        this.con.fillStyle = "rgba(0, 0, 0, 0.8)"; //填充柱形,颜色

        x_shift_index = 0
        for (var k in data) { //绘制柱形
            tag_incr = data[k]['tags_inc']
            tag_incr_length = tag_incr.length

            // 默认画一个出来，在画剩余的
            if (tag_incr_length == 0) {
                var x = this.y0 + this.step * 0.7071 * (x_shift_index)
                this.drawFont({
                    x: this.y0 + this.step * 0.7071 * x_shift_index - this.canH * 1.414 - 2 * this.step * this.canH / 200 + 215,
                    y: x - 2 * this.step * this.canH / 200 + 45,
                    text: data[k]['date'],
                    color: "rgba(0, 0, 0, 0.8)",
                    fontSizePercent: 1 / 25
                }, true);
                x_shift_index += 1
            } else {
                //for (var tag_incr_inde = 0; tag_incr_inde < tag_incr_length; tag_incr_inde++) {
                var x = this.y0 + this.step * 0.7071 * (x_shift_index)
                this.drawFont({
                    x: this.y0 + this.step * 0.7071 * x_shift_index - this.canH * 1.414 - 2 * this.step * this.canH / 200 + 209,
                    y: x - 2 * this.step * this.canH / 200 + 105,
                    text: data[k]['date'],
                    color: "rgba(0, 0, 0, 0.8)",
                    fontSizePercent: 1 / 25
                }, true);
                x_shift_index += (tag_incr_length)
            }

        }
        this.con.restore();

    }
		function getCurPlateByYHigh(y){
			// 反序的
			var map_index_2_name = {5:"first_high_count", 4:"second_high_count", 3:"third_high_count",2: "forth_high_count",
			    1:"fifth_high_count"
			}
			// var y = base_y + shift_y * y_idx
			var idx = (y - float_chart_base_y)/ float_chart_shift_y
			idx = Math.ceil(idx)
			idx = Math.max(idx, 1)
			idx = Math.min(idx, 5)
			return map_index_2_name[idx]
		}
		
	function changeRelaCodes(layerY){
		// 通过定位到的小画布y坐标和当前 底层画布的x坐标
		// console.log("cur_date:"+cur_date_status+" cur_tag : {} "+cur_tag_status+" y:"+ev.layerY)
		plate = getCurPlateByYHigh(layerY)
		try{
			var rela_code_data = get_rela_codes_by_code_tag_from_backend(cur_date_status, cur_tag_status, plate)
			var tbod = $("#tag_rela_codes_table").children("tbody")[0]
			tbod.innerHTML = ''
			var idx = 0
			for (var d_i in rela_code_data) {
			    idx++
				var d_v = rela_code_data[d_i]
				<!-- <th>列号</th> -->
				<!-- <th>股票代码</th> -->
				<!-- <th>股票名</th> -->
				// <th>股票关联涨停</th>
				// <th>标签历史涨停</th>
				<!-- <th>关联度</th> -->
				// <th>最近一次涨停时间</th> 
				
			    var tro = document.createElement("tr")
				tro.innerHTML = '<tr><td>'+idx+'</td><td>' + d_v["code"] + '</td><td>' + d_v["name"] + '</td><td>' + d_v["cur_up_times"] + '</td><td>'+d_v["cur_count"]+'</td><td>' + d_v["contribution"] + '</td><td>' + d_v["cal_date"] + '</td></tr>'
			    tbod.append(tro)
			}
		}catch(e){
			console.log(e)
		}
	}
	
    function calu_4_draw(height) {
        return Math.log2(height) * 100
    }

    function fSIndex(index) {
        var s = 0
        var e = 0
        var fi = ''
        var si = 0
        for (var ind in data) {
            fi = ind
			s = e
            e = e + Math.max(data[ind]['tags_inc'].length, 1)
            if (index >= s && index < e) {
                si = index - s
                break;
            }
        }
        return {
            "fi": fi,
            "si": si
        }
    }
	LChart.prototype.get_index_from_main_canvas_x = function(ev ){
		var that = this
			var index = 0;
			if (ev.layerX <= that.x0 + that.step + that.step / 2) {
				index = 0;
			} else if (ev.layerX > that.x0 + (x_date_length - 1) * that.step + that.step / 2) {
				index = parseInt(x_date_length - 1);
			} else {
				index = parseInt((ev.layerX - that.step - that.step / 2) / that.step);
			}
			return index
	}
    LChart.prototype.updateFloatText = function (ev) {
		index = this.get_index_from_main_canvas_x(ev)
        this.indicator.style = "position: absolute; z-index: 51; border-style: dashed; border-color: rgb(73, 73, 73);left: " +
            (((index + 1) * this.step + 0 + this.x0) + "") +
            "px; top: 20px; border-width: 0px 1px 0px 0px; height: " + ((this.canH - 135) + "") + "px;";
        // 需要转为data对应的index 前面的累加和s 后面的累加和e 对于数据 1 2 3 有 s0 0 e0 1  s2 1 e2 3
        var s = 0
        var e = 0

        data_index = 0
        for (var ind in data) {
            s = e
            e = e + Math.max(data[ind]['tags_inc'].length, 1)
            if (index >= s && index <= e) {
                break;
            }
            data_index++
        }
        // this.date.innerHTML = data[data_index]['date'];
		// 算出时间算出概念取出对应的股票信息
		// changeRelaCodes(data, index, this)
		// 重新画柱状图
		// 找出当前的日期和标签信息
        fct.rectMatrix(data, index, cur_date_status,cur_tag_status)
		changeRelaCodes(500)
		this.float_window.style =
			"position: absolute; z-index: 52; padding: 2px; width: 300px; line-height: 16px;\
		 font-size: 12px; left: " +
			(((index ) * this.step + 0 + this.x0) + "") +
			"px; top: 30px; background-color: rgba(255, 255, 255, 0.9); color: rgb(0, 0, 0);\
		  border: 1px solid rgb(0, 0, 0);"
		trf = $("#tag_rela_codes_flow")
		// css not style
		trf.css('position','absolute')
		trf.css('left',(((index ) * this.step + 0 + this.x0+305) + "")+"px")
		
		// trf.removeAttr("style")
		// trf.attr("stlye","display:None")
		// trf.attr("stlye","position: absolute; z-index: 52; padding: 2px;height:50px;width:170px;overflow:auto;background:#EEEEEE;line-height: 16px; font-size: 12px; left: 360px; top: 30px;  border: 1px solid rgb(0, 0, 0);")
		// trf.attr("stlye","position: absolute; z-index: 52; padding: 2px;height:50px;width:170px;overflow:auto;background:#EEEEEE;line-height: 16px; font-size: 12px; left: "+(((index ) * this.step + 0 + this.x0)+60 + "")+ "px; top: 30px;  border: 1px solid rgb(0, 0, 0);")
		// console.log("position: absolute; z-index: 53; padding: 2px;height:50px;width:170px;overflow:auto;background:#EEEEEE;line-height: 16px; font-size: 12px; left: "+(((index ) * this.step + 0 + this.x0)+60 + "")+ "px; top: 30px;  border: 1px solid rgb(0, 0, 0);")
		// console.log(this.float_window.style)
		
		// <div id= "tag_rela_codes_flow" style="position: absolute; z-index: 52; padding: 2px;height:50px;width:170px;overflow:auto;background:#EEEEEE;line-height: 16px; font-size: 12px; left: 360px; top: 30px;  border: 1px solid rgb(0, 0, 0);">
		
    }

	
    LChart.prototype.monitorMouse = function () {
        that = this;
        var d = document.getElementById('canvas_layer');
        d.addEventListener('mouseenter', function (ev) {
            that.float_window.style.display = "";
            that.indicator.style.display = "";
			// 更新的对应的date和tag
			ev = ev || window.event;
        })
        d.addEventListener('mousemove', function (ev) {
            ev = ev || window.event;
         line_idx = that.get_index_from_main_canvas_x(ev)
         tr_ = fSIndex(line_idx)
         f_idx = tr_['fi'];s_idx = tr_['si']
         // 获取对应的数据
         var a = data[f_idx]
         cur_date_status = data[f_idx]['date']
         cur_tag_status = data[f_idx]['tags_inc'][s_idx]['tag']
         console.log("date : "+cur_date_status+" tag:"+cur_tag_status)
			that.updateFloatText(ev);
        })
		
        d.addEventListener('mouseover', function (ev) {
            //ev = ev || window.event;
            //that.updateFloatText(ev);
        })
    }

    var lc = new LChart();

    default_send_mess_2_db = function f() {
        var market_thermometer = new XMLHttpRequest();
        market_thermometer.overrideMimeType("application/json");
        market_thermometer.open("GET", "api/stock-calendar", true);
        market_thermometer.send(null);
        market_thermometer.onreadystatechange = function () {
            if (market_thermometer.readyState == 4 && market_thermometer.status == 200) {
                all_data = JSON.parse(market_thermometer.responseText);
                parse_data(all_data)
            }
        }
    }
    parse_data = function (all_data) {
        if (all_data['api_call'] === 1) {
            // data = all_data['data'];
            // lc.gaobiao_scale = all_data['gaobiao_scale']
			lc.gaobiao_scale = 1
	// 		data = [{
	// 		"date": "2019-10-11",
	// 		"tags_inc": [{
	// 		"tag": "HW",
	// 		"incr": "22"
	// 	}]
	// }]
	data = all_data['data']
            lc.check_load_data();
        } else {
            alert(data['message'])
        }
    }
    default_send_mess_2_db();

    $(document).ready(function () {
        const Url = "api/stock-calendar";
        $('#submit_btn').click(function () {
            var jsoStr = {
                "datetimeStart": $("#datetimeStart").children("input")[0].value,
                "datetimeEnd": $("#datetimeEnd").children("input")[0].value,
                "size": $("#size")[0].value
            };
            $.ajax({
                url: Url,
                type: "POST",
                data: jsoStr,
                success: function (result) {
                    console.log(result);
                    parse_data(result)
                },
                error: function (error) {
                    console.log(error)
                    parse_data(error)
                }
            })
        })
    });

    function get_a_parse_rela_code_backend(tag_name, num = 30) {
        console.log("get tag:" + tag_name)
        //需要获取服务器的JSON
        var _data = {"tag": tag_name, "num": num}
        var Url = 'api/tag_rela'
        $.ajax({
            url: Url,
            type: "POST",
            data: _data,
            success: function (result) {
                parse_rela_code(result)
            },
            error: function (error) {
                alert("网络错误 "+error)
            }
        })


    }

    function parse_rela_code(api_data) {
        if (api_data['api_call'] == 1) {
            // data = [{"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2"},
            //     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2"},
            //     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2"},
            //     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2"},
            //     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date": "20191014", "cur_count": "2"},
            //     {"code": "300317", "name": "假的", "cur_up_times": "1", "cur_date"1: "20191014", "cur_count": "2"}]
            var data = api_data['rela_code']
            var cur_count = api_data['cur_count']
            var st = api_data['server_time']

            $("#cur_count").text(cur_count)
            $("#server_time").text(st)

            // 渲染到表格中
            var tbod = $("#tag_rela_codes_table__2").children("tbody")[0]
            tbod.innerHTML = ''
			var idx = 0
            for (var d_i in data) {
				idx+=1
                var d_v = data[d_i]
                var tro = document.createElement("tr")
<!--            <th>序号</th>-->
<!--            <th>股票代码</th>-->
<!--            <th>股票名</th>-->
<!--            <th>股票标签历史涨停次数</th>-->
<!--            <th>关联度</th>-->
<!--            <th>最近一次涨停时间</th>-->

                tro.innerHTML = '<tr><td>'+idx+'</td><td>' + d_v["code"] + '</td><td>' + d_v["name"] + '</td><td>' + d_v["cur_up_times"] + '</td><td>' + d_v["rela_ratio"] + '</td><td>' + d_v["cur_date"] + '</td></tr>'
                tbod.append(tro)
            }
        } else {
			alert(api_data['message'])
        }
    }
    // get_a_parse_rela_code_backend("a")
    //    添加输入的事件
	// 限制提交的频率
	cur_commit_times = 0
	max_commit_tiems = 150
	function get_rela_codes_by_code_tag_from_backend(selected_date, selected_tag, selected_plate){
		// 根据本地的信息进行获取 continue_stock_infos
		return continue_stock_infos[selected_plate]
		
		//需要获取服务器的JSON
		// cur_commit_times+= 1;
		// if (cur_commit_times < max_commit_tiems){
		// 	throw "limit freq"
		// 	}
		// else{
		// 	cur_commit_times = 0
		// }
		// var send_data = {"date":selected_date,"tag":selected_tag,"plate":selected_plate}
		// var Url = 'api/rela_code_by_d_t_p'
		// res_backend_ = {}
		// $.ajax({
		//     url: Url,
		//     type: "POST",
		//     data: send_data,
		// 	async : false,
		//     success: function (result) {
		// 		if (result['api_call'] == 1){
		// 			res_backend_ = result
		// 		}else{
		// 			alert("错误:"+result)
		// 		}
		//     },
		//     error: function (error) {
		//         alert(error)
		//     }
		// })
		// return res_backend_['data'];
	}
	
    $("#in_tag").bind('keyup', function (event) {
        if (event.keyCode === 13) {
            // 刷新数据
            get_a_parse_rela_code_backend($('#in_tag').val())
        }
    });
	
	var fct = new FloatChart();
	fct.init()
	lc.monitorMouse()
	function in_a(idx){
	}
	
	pre_date_4_csi = 'csi'
	pre_tag_4_tag = 'csi'
	function generate_continue_stock_infos_from_backend(cur_date, cur_tag){
		// 进行比对防止重复进行请求
		if (pre_date_4_csi == cur_date && pre_tag_4_tag == cur_tag){
			throw "same req"
		}
		pre_date_4_csi = cur_date 
		pre_tag_4_tag = cur_tag
		send_data = {"cur_date":cur_date,"cur_tag":cur_tag}
		$.ajax({
		    url: "api/continue_stock_info",
		    type: "POST",
		    data: send_data,
			async : false,
		    success: function (result) {
				if (result['api_call'] == 1){
					res_backend_ = result
				}else{
					alert("错误:"+result)
				}
		    },
		    error: function (error) {
		        alert("网络错误 "+error)
		    }
		})
		return res_backend_['data'];
		
	}
</script>
